package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.PopwindowMapGoodsBinding;
import com.sgb.kjwl.model.entity.transport.MapSourcesEntity;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.link.utils.LogisticsLogUtils;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.ui.activity.transport.InquireByLetterActvity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.dialog.RoundDialog;

/**
 * @author: 杨畔
 * @date: 2021/8/17 12:04
 * @Description: 图查货源弹窗
 */
public class MapGoodsPopWindow extends BasePopWindow<Object> implements View.OnClickListener {

    private PopwindowMapGoodsBinding mBinding;
    private MapSourcesEntity mEntity;
    //消息回调
    private OnClickCallBack mCallListener;

    public interface OnClickCallBack {
        void message(String account);
    }

    public void setOnClickCallBack(OnClickCallBack onClickCallBack) {
        this.mCallListener = onClickCallBack;
    }

    @Override
    protected int popLayout() {
        return R.layout.popwindow_map_goods;
    }

    public MapGoodsPopWindow(Context context) {
        super(context, DIR_DOWN_UP);
    }

    @Override
    protected void initView(PopViewHolder holder) {
        mBinding = (PopwindowMapGoodsBinding) holder.getmBinding();
        mBinding.setOnClick(this);
    }

    public void setData(MapSourcesEntity entity) {
        if (entity == null) return;
        mEntity = entity;
        //装卸地
        mBinding.tvPlace.setText(String.format("%s %s ➞ %s %s",
                entity.getCityName(),
                entity.getDistrictName(),
                entity.getDestCityName(),
                entity.getDestDistrictName()));
        //距离
        if (!TextUtils.isEmpty(entity.getDistance())) {
            double distance = NumberUtil.convertToDouble(entity.getDistance());
            mBinding.tvDistance.setText(distance < 1000
                    ? "距您1km以内"
                    : String.format("距您%skm", NumberUtil.trim0(distance / 1000)));
        } else {
            mBinding.tvDistance.setText("");
        }
        //货源信息
        StringBuilder goodsBuilder = new StringBuilder(CargoConstant.getLastGoodsTypeName(entity.getGoodsTypeName(), entity.getSecondGoodsTypeName()));
        if (!TextUtils.isEmpty(entity.getWeight())) {
            goodsBuilder.append("/").append(NumberUtil.trim0(entity.getWeight())).append("吨");
        }
        if (!TextUtils.isEmpty(entity.getVolume())) {
            goodsBuilder.append("/").append(NumberUtil.trim0(entity.getVolume())).append("方");
        }
        mBinding.tvGoods.setText(goodsBuilder);
        //装货时间调整
        String loadTime = CargoConstant.stampFormatListLoadTime(
                entity.getShipmentTime(), entity.getStartPointTime(),
                entity.getShipmentEndTime(), entity.getEndPointTime());
        if (!TextUtils.isEmpty(loadTime)) {
            mBinding.loadTime.setText(String.format("%s 装货", loadTime));
        } else {
            mBinding.loadTime.setVisibility(View.GONE);
        }
        //判断是否可拨打电话
        if (TextUtils.isEmpty(entity.getContrctsImAccount())) {
            mBinding.tvMsg.setAlpha(0.5F);
            mBinding.tvMsg.setEnabled(false);
        } else {
            mBinding.tvMsg.setAlpha(1F);
            mBinding.tvMsg.setEnabled(true);
        }
        //判断是否可联系
        if (TextUtils.isEmpty(entity.getContrctsNumber())) {
            mBinding.tvTel.setEnabled(false);
            mBinding.tvTel.setAlpha(0.5F);
        } else {
            mBinding.tvTel.setEnabled(true);
            mBinding.tvTel.setAlpha(1f);
        }
/*        if (entity.getPattern() == 1) {
            //竞价货源
            mBinding.ivPattern.setVisibility(View.VISIBLE);
            mBinding.ivLoadType.setVisibility(View.GONE);
            //报价资格 1 企业 2 团队 3 司机
            if (!TextUtils.isEmpty(entity.getOfferType())) {
                String offerType = entity.getOfferType()
                        .replaceAll(",", "/")
                        .replace("1", "企业")
                        .replace("2", "团队")
                        .replace("3", "个人（司机）");
                mBinding.tvContentView.setText(String.format("报价资格：%s", offerType));
            } else {
                mBinding.tvContentView.setText("");
            }
            //运费/运费单价
            mBinding.tvMsgFee.setVisibility(View.VISIBLE);
            mBinding.tvMsgFee.setText(!TextUtils.isEmpty(entity.getAllFreight())
                    ? mContext.getResources().getString(R.string.app_the_freight_combined) + String.format(" %s元", NumberUtil.trim0(entity.getAllFreight()))
                    : "");
            mBinding.tvFreight.setText(!TextUtils.isEmpty(entity.getFreight())
                    ? String.format("运费单价 %s元%s", NumberUtil.trim0(entity.getFreight()), entity.getFreightUnitWords())
                    : "");
        } else {*/
        if (entity.getPattern() == 1) {//竞价货源
            mBinding.ivPattern.setVisibility(View.VISIBLE);
        } else {//普通货源
            mBinding.ivPattern.setVisibility(View.GONE);
        }
        //用车类型
//        String loadTypeStr = CargoConstant.getTransportTypeStr(entity.getTransportType());
//        if ("零担".equals(loadTypeStr)) {
//            mBinding.ivLoadType.setVisibility(View.VISIBLE);
//            mBinding.ivLoadType.setImageResource(R.drawable.icon_less_than_tag);
//        } else if ("整车".equals(loadTypeStr)) {
//            mBinding.ivLoadType.setVisibility(View.VISIBLE);
//            mBinding.ivLoadType.setImageResource(R.drawable.icon_carload_tag);
//        } else {
//            mBinding.ivLoadType.setVisibility(View.GONE);
//        }
        //车辆信息
        StringBuilder carBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(entity.getCarTypeName())) {
            carBuilder.append(entity.getCarTypeName().replaceAll(",", "/"));
        }
        if (!TextUtils.isEmpty(entity.getCarLenName())) {
            carBuilder.append("\u3000");
            carBuilder.append(entity.getCarLenName().replaceAll(",", "/"));
        }
        if (!TextUtils.isEmpty(entity.getHeightHurdle())) {
            carBuilder.append("\u3000");
            carBuilder.append("栏高").append(NumberUtil.trim0(entity.getHeightHurdle())).append("米");
        }
        if (entity.getIsDump() != null) {
            carBuilder.append("\u3000");
            carBuilder.append(VehicleConstant.getIsDumpStr(entity.getIsDump()));
        }
        mBinding.tvContentView.setText(carBuilder.toString());
        //信息费/运费
        if (!TextUtils.isEmpty(entity.getMessagePrice()) && !NumberUtil.trim0(entity.getMessagePrice()).equals("0")) {
            mBinding.tvMsgFee.setVisibility(View.VISIBLE);
            mBinding.tvMsgFee.setText(String.format("信息费 %s元", NumberUtil.trim0(entity.getMessagePrice())));
        } else {
            mBinding.tvMsgFee.setText("");
            mBinding.tvMsgFee.setVisibility(View.GONE);
        }
        // 一口价/电议
        if (entity.getFreightType() == 1) {
            mBinding.tvFreight.setText("运费合计 电议");
        } else {
            mBinding.tvFreight.setText(!TextUtils.isEmpty(entity.getAllFreight())
                    ? mContext.getResources().getString(R.string.app_the_freight_combined) + String.format(" %s元", NumberUtil.trim0(entity.getAllFreight()))
                    : "");
        }
    }

    @Override
    public void onClick(View v) {
        if (mEntity == null) return;
        if (v == mBinding.tvMsg) {
            if (mCallListener != null) {
                if (mEntity != null) {
                    // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                    if (!TextUtils.isEmpty(mEntity.getContrctsImAccount())) {
                        mCallListener.message(mEntity.getContrctsImAccount());
                    } else {
                        if (!TextUtils.isEmpty(mEntity.getImAccount())) {
                            mCallListener.message(mEntity.getImAccount());
                        }
                    }
                }
            }
        } else if (v == mBinding.tvTel) {
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            if (!TextUtils.isEmpty(mEntity.getConnectionPhone())) {
                showTelDialog();
            }
        } else if (v == mBinding.tvInvite) {
            //todo 邀请
            LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, mEntity.getCompanyNo(), mEntity.getTerminal());
        } else if (v == mBinding.tvInquireByLetter) {
            //函询
            if (UserOperating.getInstance().isNotLogged(mContext)) {
                return;
            }
            InquireByLetterActvity.start(mContext, mEntity.getPattern(),
                    mEntity.getContrcts(), mEntity.getUserNo(), mEntity.getNo(),
                    String.format("%s %s->%s %s",
                            mEntity.getCityName(),
                            mEntity.getDistrictName(),
                            mEntity.getDestCityName(),
                            mEntity.getDestDistrictName())
            );
        } else if (v == mBinding.llInfo) {
            //跳转货源详情
            if (mEntity.getPattern() == 1) {
                FreightPrjDetailActivity.start(mContext, mEntity.getNo(), false, false);
            } else {
                GeneralPrjDetailActivity.start(mContext, mEntity.getNo(), mEntity.getPattern(), false);
            }
        } else if (v == mBinding.tvQuote) {
            //报价逻辑
//            if (mEntity.getPattern() == 1) {
//                LogisticsPermissionHelper.getInstance().checkPermissionToQuote(
//                        mContext, mEntity.getNo(), mEntity.getTerminal(), mEntity.getMessagePrice()
//                );
//            } else {
                LogisticsPermissionHelper.getInstance().checkPermissionToOrderQuote(
                        mContext, mEntity.getNo(), mEntity.getTerminal(), mEntity.getMessagePrice()
                );
//            }
        } else if (v == mBinding.tvOrder) {
            //接单逻辑
//            if (mEntity.getPattern() == 1) {
//                //竞价货源接单逻辑
//                LogisticsPermissionHelper.getInstance().checkPermissionToQuoteOrder(
//                        mContext, mEntity.getNo(), mEntity.getTerminal(), mEntity.getMessagePrice()
//                );
//            } else {
                LogisticsPermissionHelper.getInstance().checkPermissionToOrder(
                        mContext, mEntity.getNo(), mEntity.getTerminal(), mEntity.getMessagePrice()
                );
//            }
        }
    }

    /**
     * 电话弹窗
     */
    private void showTelDialog() {
        new RoundDialog.Builder(mContext)
                .title("确认呼叫")
                .content(mEntity.getConnectionPhone())
                .confirm("确定")
                .cancel("取消")
                .confirmCallback(v -> {

                    LogisticsLogUtils.getInstance().logisticsFlow("5", "货源联系人", "icon");
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + mEntity.getConnectionPhone());
                    intent.setData(data);
                    mContext.startActivity(intent);
                })
                .show();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        clearAlpha();
    }
}
